package org.example.utils;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.*;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.example.entity.es.Tehero;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;

public class ESClient {

    private static final Logger log = LoggerFactory.getLogger(ESClient.class);
    private static String hosts = "192.168.150.161:9201";
    private static String username = "elastic";
    private static String passwd = "123456";
    private static String apikey;
    private static RestClient restClient;
    private static ElasticsearchTransport transport;

    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = clientByPasswd();
        Query query=new TermQuery.Builder().field("").value("").build()._toQuery();
        SearchRequest searchRequest=SearchRequest.of(m->m.index("tehero_index"));
        List<Tehero> list = search(client, searchRequest, Tehero.class);
        close();
//        RestClient httpClient = RestClient.builder(
//                new HttpHost("192.168.150.161", 9201)
//        ).build();
//        ElasticsearchTransport transport = new RestClientTransport(
//                httpClient,
//                new JacksonJsonpMapper()
//        );
//        ElasticsearchClient esClient = new ElasticsearchClient(transport);
//        SearchRequest searchRequest = SearchRequest.of(m -> m.index("tehero_index"));
//        List<Tehero> list = search(esClient, searchRequest, Tehero.class);
//        httpClient.close();
//        transport.close();
    }

    public static <T> List<T> search(ElasticsearchClient client, SearchRequest searchRequest, Class<T> clazz) throws IOException {
        SearchResponse<T> response = client.search(searchRequest, clazz);
        List<Hit<T>> hits = response.hits().hits();
        List<T> list = new ArrayList<>();
        for (Hit<T> hit : hits)
            list.add(hit.source());
        return list;
    }

    private static HttpHost[] toHttpHost() {
        return toHttpHost(true);
    }

    private static HttpHost[] toHttpHost(boolean isHttps) {
        if (!StringUtils.hasLength(hosts)) {
            throw new RuntimeException("invalid elasticsearch configuration");
        }
        String[] hostArray = hosts.split(",");
        HttpHost[] httpHosts = new HttpHost[hostArray.length];
        HttpHost httpHost;
        for (int i = 0; i < hostArray.length; i++) {
            String[] strings = hostArray[i].split(":");
            httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), isHttps ? "https" : "http");
            httpHosts[i] = httpHost;
        }

        return httpHosts;
    }

    public static ElasticsearchClient clientByPasswd() throws Exception {
        transport = getElasticsearchTransport(username, passwd, toHttpHost());
        return new ElasticsearchClient(transport);
    }

    private static SSLContext buildSSLContext() {
        ClassPathResource resource = new ClassPathResource("http_ca.crt");
        SSLContext sslContext = null;
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            Certificate trustedCa;
            try (InputStream is = resource.getInputStream()) {
                trustedCa = factory.generateCertificate(is);
            }
            KeyStore trustStore = KeyStore.getInstance("pkcs12");
            trustStore.load(null, null);
            trustStore.setCertificateEntry("ca", trustedCa);
            SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, null);
            sslContext = sslContextBuilder.build();
        } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException |
                 KeyManagementException e) {
            log.error("ES连接认证失败", e);
        }

        return sslContext;
    }

    private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost... hosts) {
        // 账号密码的配置
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));

        // 自签证书的设置，并且还包含了账号密码
        HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
                .setSSLContext(buildSSLContext())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setDefaultCredentialsProvider(credentialsProvider);

        // 用builder创建RestClient对象
        restClient = RestClient.builder(hosts)
                .setHttpClientConfigCallback(callback)
                .build();
        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }

    private static ElasticsearchTransport getElasticsearchTransport(String apiKey, HttpHost... hosts) {
        // 将ApiKey放入header中
        Header[] headers = new Header[]{new BasicHeader("Authorization", "ApiKey " + apiKey)};

        // es自签证书的设置
        HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
                .setSSLContext(buildSSLContext())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

        // 用builder创建RestClient对象
        restClient = RestClient
                .builder(hosts)
                .setHttpClientConfigCallback(callback)
                .setDefaultHeaders(headers)
                .build();

        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }

    public static ElasticsearchClient clientByApiKey() throws Exception {
        transport = getElasticsearchTransport(apikey, toHttpHost());
        return new ElasticsearchClient(transport);
    }

    public static void close() {
        try {
            if (restClient != null) {
                restClient.close();
            }
            if (transport != null)
                transport.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

